<template>
  <div class="app-container">
    <el-row>
      <!--区域数据-->
      <el-col :xs="24" v-show="treeVisibale === true" class="tree_bg">
        <!-- <div>
          <el-input
            v-model="keyWordName"
            placeholder="输入关键字进行过滤"
            clearable
            size="small"
            prefix-icon="el-icon-search"
            style="margin-bottom: 20px"
          />
        </div> -->
        <div class="head-container">
          <el-tree
            :data="areaOptions"
            :props="defaultProps"
            :expand-on-click-node="false"
            :filter-node-method="filterNode"
            ref="tree"
            node-key="id"
            default-expand-all
            highlight-current
            @node-click="handleNodeClick"
            v-loading="treeloading"
          />
        </div>
        <div class="tree_close" @click="changeTreeShow">
          <i class="el-icon-caret-left" style="color: white"></i>
        </div>
      </el-col>
      <el-col class="jiange"></el-col>
      <div class="tree_open" @click="changeTreeShow" v-show="treeVisibale === false">
        <i class="el-icon-caret-right" style="color: white"></i>
      </div>
      <el-col :xs="24" :class="treeVisibale ? 'table_small_bg' : 'table_big_bg'">
        <el-row class="line-bottom" v-show="showSearch">
          <el-col class="form_col">
          <el-form :model="queryParams" ref="queryForm" :size="size" v-show="showSearch" :label-width="labelWidth">
            <div id="searchFilter" :gutter="10" style="display: flex; flex-wrap: wrap">
              <el-form-item label="楼栋名" prop="ldName">
                <el-input
                  v-model="queryParams.ldName"
                  placeholder="请输入楼栋名"
                  clearable
                  @keyup.enter.native="handleQuery"
                  size="small"
                />
              </el-form-item>
            </div>
            </el-form>
          </el-col>
          <el-col class="form_query">
            <el-button v-show="collapseAble" type="text" @click="shiftCollapseAble" class="text">
              <span>
                {{ fold ? '收起筛选' : '更多筛选' }}
              </span>
            </el-button>
            <el-button type="primary" @click="handleQuery" size="mini">查询</el-button>
            <el-button @click="resetQuery" size="mini">重置</el-button>
          </el-col>
        </el-row>
        <el-row :gutter="10" class="mb8 padding_top_bottom">
          <el-col :span="1.5">
            <el-button
              type="primary"
              plain
              icon="el-icon-plus"
              size="mini"
              @click="handleAdd"
              v-hasPermi="['basedata:loudong:add']"
            >新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="danger"
              plain
              icon="el-icon-delete"
              size="mini"
              :disabled="multiple"
              @click="handleDelete"
              v-hasPermi="['basedata:loudong:remove']"
            >批量删除</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="info"
              plain
              icon="el-icon-upload2"
              size="mini"
              @click="handleImport"
            >导入</el-button>
          </el-col>
          <RightDropdown :columns="columns" :showSearch.sync="showSearch" @queryTable="getList" @export="handleExport" :hasPermiExport="['basedata:loudong:export']"></RightDropdown>
        </el-row>

        <el-table v-loading="loading" :data="loudongList" @selection-change="handleSelectionChange" max-height="600" ref="table">
          <el-table-column type="selection" width="55" align="center" fixed/>
          <!-- <el-table-column label="平台表单主键" align="center" prop="ID" width="120" v-if="false" :show-overflow-tooltip="true"/> -->
          <!-- <el-table-column label="租户编号" align="center" prop="tenantId" v-if="true" :show-overflow-tooltip="true"/> -->
          <el-table-column label="区域编码" align="center" prop="areaCode" v-if="false" :show-overflow-tooltip="true"/>
          <el-table-column label="区域名称" align="center" prop="areaName" v-if="columns[1].visible" :show-overflow-tooltip="true"/>
          <el-table-column label="楼栋编号" align="center" prop="ldId" v-if="false" :show-overflow-tooltip="true"/>
          <el-table-column label="楼栋名" align="center" prop="ldName" v-if="columns[3].visible" :show-overflow-tooltip="true"/>
          <el-table-column label="地上层数" align="center" prop="overground" v-if="columns[4].visible" :show-overflow-tooltip="true"/>
          <el-table-column label="地下层数" align="center" prop="underground" v-if="columns[5].visible" :show-overflow-tooltip="true"/>
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="120" fixed="right">
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="handleUpdate(scope.row)"
                v-hasPermi="['basedata:loudong:edit']"
              >修改</el-button>
              <el-button
                size="mini"
                type="text"
                icon="el-icon-delete"
                @click="handleDelete(scope.row)"
                v-hasPermi="['basedata:loudong:remove']"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <pagination
          v-show="total>0"
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
        />
      </el-col>
    </el-row>

    <!-- 添加或修改楼栋对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="680px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" :label-width="labelWidth" :inline="true">
        <el-form-item label="归属水司" prop="tenantId">
          <el-select v-model="form.tenantId" placeholder="请选择归属水司" style="width: 202px;">
            <el-option
              v-for="dict in dict.type.belong_department"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value.toString()"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="区域名称" prop="areaCode">
          <!-- <el-select v-model="form.areaCode" placeholder="请输入区域名称" style="width: 202px;" clearable>
            <el-input
              v-model="AreaName"
              placeholder="输入关键字进行过滤"
              clearable
              size="small"
              style="width: 80%;margin-left: 10%;"
              />
            <el-option class="option" :value="selectOptions.value" :label="selectOptions.label" :key="selectOptions.value">
              <el-tree
                :data="areaOptions"
                :props="defaultProps"
                :expand-on-click-node="false"
                :filter-node-method="filterNode"
                ref="areatree"
                node-key="id"
                default-expand-all
                highlight-current
                @node-click="handleSelectTree"
                class="tree"
              />
            </el-option>
          </el-select> -->
          <treeselect v-model="form.areaCode" :options="areaOptions" :normalizer="normalizer" :show-count="true" placeholder="请选择区域名称" style="width:202px;"/>
        </el-form-item>
        <el-form-item label="楼栋名" prop="ldName">
          <el-input v-model="form.ldName" placeholder="请输入楼栋名" />
        </el-form-item>
        <el-form-item label="地上层数" prop="overground">
          <el-input v-model="form.overground" placeholder="请输入地上层数" />
        </el-form-item>
        <el-form-item label="地下层数" prop="underground">
          <el-input v-model="form.underground" placeholder="请输入地下层数" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <div class="el-upload__tip" slot="tip">
            <el-checkbox v-model="upload.updateSupport" /> 是否更新已经存在的用户数据
          </div>
          <span>仅允许导入xls、xlsx格式文件。</span>
          <!-- <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;" @click="importTemplate">下载模板</el-link> -->
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listLoudong, getLoudong, delLoudong, addLoudong, updateLoudong } from "@/api/record/loudong";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import { getToken } from "@/utils/auth";

export default {
  name: "Loudong",
  dicts: ['warnparamtype', 'warntargettype', 'belong_department', 'module_type'],
  components: { Treeselect },
  data() {
    return {
      // 导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/basedata/loudong/importData"
      },
      // selectOptions:{},
      size:'small',
      collapseAble: false,
      fold: false,
      maxShow: '3',
      labelWidth: '90px',
      // 列信息
      columns: [
        // { key: 0, label: `编号`, visible: false },
        // { key: 1, label: `租户编号`, visible: true },
        { key: 0, label: `区域编码`, visible: true },
        { key: 1, label: `区域名称`, visible: true },
        { key: 2, label: `楼栋编号`, visible: true },
        { key: 3, label: `楼栋名`, visible: true },
        { key: 4, label: `地上层数`, visible: true },
        { key: 5, label: `地下层数`, visible: true },
      ],
      defaultProps: {
        children: "children",
        label: "label"
      },
      AreaName:'',
      // 区域树选项
      areaOptions: [],
      // 区域名称
      keyWordName: undefined,
      // 树状态
      treeVisibale: true,
      // 遮罩层
      loading: true,
      treeloading: true,
      // 选中数组
      ids: [],
      ldnames: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 楼栋表格数据
      loudongList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 20,
        ldName: null,
        treeAreaCode: null,
        treeLdId: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        // tenantId: [
        //   { required: true, message: "租户ID不能为空", trigger: "blur" }
        // ],
        ldName: [
        { required: true, message: "楼栋名不能为空", trigger: "blur" }
        ],
        areaCode: [
          { required: true, message: "请选择区域", trigger: "change" }
        ],
        overground: [
          { required: true, message: "地上层数不能为空", trigger: "blur" }
        ],
        createTime: [
          { required: true, message: "创建时间不能为空", trigger: "blur" }
        ]
      }
    };
  },
  created() {
    this.getList();
    this.getAreaTree();
  },
  mounted() {
    // 通过最大显示个数控制展开/折叠
    if (this.maxShow > 0) {
      this.minShowControl()
    }
  },
  watch: {
    // 根据名称筛选区域树
    keyWordName(val) {
      this.$refs.tree.filter(val);
    },
    // AreaName(val){
    //   this.$refs.areatree.filter(val)
    // }
  },
  methods: {
     /** 导入按钮操作 */
     handleImport() {
      this.upload.title = "楼栋导入";
      this.upload.open = true;
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", { dangerouslyUseHTMLString: true });
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },
      //去掉children=null的属性
    normalizer(node){
      if(node.children==null||node.children=='null'){
        delete node.children;
      }
    },
    // 展开折叠按钮
    shiftCollapseAble() {
      this.fold = !this.fold
      this.minShowControl()
    },
    // 通过maxShow控制元素显示/折叠
    minShowControl() {
      const group = window.document.querySelectorAll(`#searchFilter .el-form-item.el-form-item--${this.size}`)
      const len = group?.length ? group?.length - 1 : 0
      if (this.maxShow < len) {
        group.forEach((item, index) => {
          if (index > this.maxShow - 1 && index < len) {
            item.hidden = !this.fold
          }
        })
        this.collapseAble = true
      } else {
        this.collapseAble = false
      }
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    // 节点单击事件
    handleNodeClick(data) {
      this.queryParams.treeAreaCode = data.id;
      this.handleQuery();
    },
    // 单击下拉框中的数据
    handleSelectTree(data){
      // this.selectOptions.label = data.label
      // this.selectOptions.value = data.id
      this.form.areaCode = data.id
    },
    /** 查询区域下拉树结构 */
    getAreaTree() {
      this.treeloading = true
      let list_ = JSON.parse(localStorage.getItem('list'))
      list_.forEach((item) => {
        var obj = {
          id: item.areaCode,
          label: item.areaName,
          children: item.children && item.children.length > 0 ? this.copyTree(item.children) : item.children
        }
        this.areaOptions.push(obj)
      })
      this.treeloading = false
    },
    copyTree(list) {
      list.forEach((item) => {
        item.id = item.areaCode;
        item.label = item.areaName;
        item.children = item.children;
        if (item.children && item.children.length) {
          this.copyTree(item.children);
        }
      });
      return list;
    },
    // 改变tree的显示与隐藏
    changeTreeShow(){
      this.treeVisibale =!this.treeVisibale
    },
    /** 查询楼栋列表 */
    getList() {
      this.loading = true;
      listLoudong(this.queryParams).then(response => {
        this.loudongList = response.rows;
        this.$nextTick(() => {
          window.setTimeout(() => {
            this.$refs.table.doLayout()
          }, 100)
        })
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.areaName = ''
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        ID: null,
        tenantId: '710170',
        areaCode: null,
        ldId: null,
        ldName: null,
        overground: null,
        underground: null,
        createTime: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.$nextTick(() => {
        this.$refs.tree.setCurrentKey(null)
      })
      this.queryParams.treeAreaCode = ''
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.ldnames = selection.map(item => item.ldName)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加楼栋";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const ID = row.id || this.ids
      getLoudong(ID).then(response => {
        this.form = response.data;
        // this.form.areaCode = row.areaName
        this.open = true;
        this.title = "修改楼栋";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.title === "修改楼栋") {
            updateLoudong(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else if(this.title === "添加楼栋") {
            debugger
            addLoudong(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const IDs = row.id || this.ids;
      const LdIDs = row.ldName || this.ldnames
      this.$modal.confirm('是否确认删除楼栋名称为"' + LdIDs + '"的数据项？').then(function() {
        return delLoudong(IDs);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('basedata/loudong/export', {
        ...this.queryParams
      }, `loudong_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
<style lang="scss" scoped>
    // .el-button--text.is-active, .el-button--text:active {
    //   color: #67C23A !important;
    // }
    // .el-button--text:focus, .el-button--text:hover {
    //   color: #67C23A !important;
    // }
    .option {
        height: auto;
        line-height: 1;
        padding: 0;
        background-color: #fff;
    }
    .tree {
        padding: 4px 20px;
        font-weight: 400;
    }
    .form_col{
    width: 80%;
    ::v-deep .el-form {
      width: 100%;
    }
    ::v-deep .el-form-item {
      width: 25%;
    }
  }
  .form_query{
    width: 20%;
    text-align: right;
  }
  </style>
